import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by LuoTao on 2016/10/25.
 * LemonTech Copyright reserved.
 */
public class DBHelper {

    private static Map<String,String> JDBCCorrespond = new HashMap<>();
    private static Logger log = LogManager.getLogger(DBHelper.class);
    static {
        JDBCCorrespond.put("mysql","com.mysql.jdbc.Driver");
        JDBCCorrespond.put("hive2","org.apache.hive.jdbc.HiveDriver");
    }

    public static Connection getConnection(String dbType,String host,String username,String password,String DBName){
        Connection conn = null;
        if(!JDBCCorrespond.containsKey(dbType)){
            log.error("没有指定类型的jdbc");
            return conn;
        }
        try {
            Class.forName(JDBCCorrespond.get(dbType));
            //需要配置编码格式为UTF-8，否则中间就会出现中文无法解析
            if (username == null) {
                username = "";
            }
            if (password == null) {
                password = "";
            }
            conn = DriverManager.getConnection("jdbc:" + dbType + "://" + host + "/" + DBName + "?characterEncoding=UTF-8", username, password);
        } catch (ClassNotFoundException e) {
            log.error(JDBCCorrespond.get(dbType)+" 找不到指定类");
            e.printStackTrace();
        } catch (SQLException e) {
            log.error("连接创建失败");
            e.printStackTrace();
        }
        return conn;
    }

    public static Connection getConnection(Config config) {
        return getConnection(config.getJdbc(), config.getHost(), config.getUsername(), config.getPassword(), config.getDatabase());
    }
}
